package com.hdoit.jiayuntong.camera;

import com.hdoit.jiayuntong.entity.LocalPictureSelectedStatus;
import com.hdoit.jiayuntong.entity.Picture;

import java.io.IOException;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.IBinder;

public class DataHandlerService extends Service {

	public static final String ACTION = "com.hdoit.jiayuntong.camera.DataHandlerService.action.UPDATE";
    private Thread jobThread;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
    
	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		jobThread = new Thread(new Runnable() {
			@Override
			public void run() {
				List<Picture> pics = PictureManager.Instance().getPictures();
				for(int i = 0; i < pics.size(); i ++){
					if(pics.get(i).status == LocalPictureSelectedStatus.None){
						Bitmap bm  = PictureStorageUtil.getBitmap(pics.get(i).getFilePath());
						try {
							pics.get(i).setUsedToUpload(PictureCompressUtil.compressImageBySize(bm,200));
							pics.get(i).status = LocalPictureSelectedStatus.AllowedToUpload;
						} catch (IOException e) {
							e.printStackTrace();
						}
						
						Intent intent = new Intent(ACTION);
						intent.putExtra("flag", "update");
						sendBroadcast(intent);
					}
				}
				Intent intent = new Intent(ACTION);
				intent.putExtra("flag", "finish");
				sendBroadcast(intent);
			}
		});
		jobThread.start();
		
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		try {
			jobThread.join();
			jobThread = null;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}
}
